<template>
    <div v-loading="loading">
        <!-- 图片上传 -->
        <div v-if="itemData.type=='image' || itemData.type=='imageMore'">
            <!-- 单张 -->
            <div v-if="itemData.type=='image'">
                <el-upload
                    class="avatar-uploader"
                    action
                    :http-request="uploadHttp"
                    :show-file-list="false"
                    :before-upload="imageBefore"
                >
                    <img
                        v-if="imgUrl"
                        :src="imgUrl"
                        class="avatar"
                        :style="'width:'+itemData.width+'px;height:'+itemData.height+'px;line-height:'+itemData.height+'px;'"
                    />
                    <i
                        v-else
                        class="el-icon-plus avatar-uploader-icon"
                        :style="'width:'+itemData.width+'px;height:'+itemData.height+'px;line-height:'+itemData.height+'px;'"
                    ></i>
                </el-upload>
            </div>
            <!-- 多张 -->
            <div v-else>
                <el-upload
                    action
                    list-type="picture-card"
                    :on-remove="imageMoreRemove"
                    :http-request="uploadHttp"
                    :before-upload="imageBefore"
                    :file-list="imageMoreUrl"
                    :limit="itemData.limit"
                    :on-exceed="imgMax"
                >
                    <i class="el-icon-plus"></i>
                </el-upload>
            </div>
        </div>
        <!-- 视频上传 -->
        <div v-if="itemData.type=='mvideo'||itemData.type=='svideo'">
            <el-upload
                class="upload-demo"
                :limit="1"
                action
                :before-upload="videoBefore"
                :file-list="videoUrlArr"
                :on-preview="vidPreview"
                :on-exceed="handleExceed"
                :http-request="uploadHttp"
            >
                <el-button size="small" type="primary">文件上传</el-button>
                <span style="margin-left:20px;" slot="tip" class="el-upload__tip">只能上传可播放文件，且不超过200M</span>
            </el-upload>
            <el-dialog
                class="vidDialog"
                top="5vh"
                title="视频预览"
                width="500px"
                :destroy-on-close="true"
                :visible.sync="dialogFormVisible"
                v-if="dialogFormVisible"
                :append-to-body="true"
            >
                <videos ref="videoPart" :videoSrc="videoUrlArr"></videos>
            </el-dialog>
        </div>
        <!-- zip上传 -->
        <div v-if="itemData.type=='file'">
            <el-upload
                class="upload-demo"
                :limit="1"
                action
                :before-upload="fileBefore"
                :file-list="zipUrlArr"
                :http-request="uploadHttp"
                :on-exceed="handleExceed"
                :before-remove="beforeRemove"
            >
                <el-button slot="trigger" size="small" type="primary">文件上传</el-button>
                <span style="margin-left:20px;" slot="tip" class="el-upload__tip">只能上传zip文件，且不超过200M</span>
            </el-upload>
        </div>
    </div>
</template>
<script>
    import Videos from "@/components/plugins/video";
    import ossClient from "@/helper/aliyun.oss.client";
    export default {
        name: "upload",
        components: { Videos },
        props: {
            itemData: {
                type: Object,
                default() {
                    return {};
                }
            },
            imgUrl: {
                type: String,
                default() {
                    return "";
                }
            },
            videoUrl: {
                type: String,
                default() {
                    return "";
                }
            },
            fileUrl: {
                type: String,
                default() {
                    return "";
                }
            },
            imgUrlArr: {
                type: String,
                default() {
                    return "";
                }
            }
        },
        data() {
            return {
                firstUpImg: true,
                loading: false,
                zipUrlArr: [],
                videoUrlArr: [],
                dialogFormVisible: false,
                imageMoreUrl: []
            };
        },
        created() {
            this.init();
        },

        watch: {
            fileUrl: {
                handler() {
                    if (this.fileUrl && typeof this.fileUrl == "string") {
                        const arr = this.fileUrl.split("*");
                        this.zipUrlArr = [{ name: arr[arr.length - 1], url: this.fileUrl }];
                    }
                }
            },

            videoUrl: {
                handler() {
                    if (this.videoUrl && typeof this.videoUrl == "string") {
                        const arr = this.videoUrl.split("*");
                        this.videoUrlArr = [
                            { name: arr[arr.length - 1], url: this.videoUrl }
                        ];
                    }
                },
                deep: true,
                immediate: true
            },

            imgUrlArr: {
                handler() {
                    if (this.firstUpImg) {
                        if (this.imgUrlArr && typeof this.imgUrlArr == "string") {
                            const arr = this.imgUrlArr.split(",");
                            arr.forEach((e, i) => {
                                this.imageMoreUrl.push({ url: e, name: e, uid: e });
                            });
                        }
                    }
                },
                deep: true,
                immediate: true
            }
        },
        methods: {
            // 上传初始化
            init() {
                let data = {};
                switch (this.itemData.type) {
                    case "image":
                        data.contentType = "images";
                        break;
                    case "imageMore":
                        data.contentType = "images";
                        break;
                    case "mvideo":
                        data.contentType = "mvideos";
                        break;
                    case "svideo":
                        data.contentType = "svideos";
                        break;
                    case "file":
                        data.contentType = "files";
                        break;
                    // default:
                    //   break;
                }
                this.$apis.system.upload(data).then(({ data }) => {
                    this.uploadConfig = data.data;
                });
            },
            imageBefore(file) {
                const isJPG =
                    file.type === "image/jpeg" ||
                    file.type === "image/bmp" ||
                    file.type === "image/png" ||
                    file.type === "image/webp";
                const isLt2M = file.size / 1024 / 1024 < 20;
                if (!isJPG) {
                    this.$message.error("上传图片只能是 bmp/jpg/png/webp 格式!");
                } else if (!isLt2M) {
                    this.$message.error("上传图片大小不能超过 20MB!");
                }
                return isJPG && isLt2M;
            },
            fileBefore(file) {
                const isJPG =
                    file.type === "application/zip" ||
                    file.type === "application/x-zip-compressed";
                const isLt2M = file.size / 1024 / 1024 < 200;
                if (!isJPG) {
                    this.$message.error("上传文件只能是 ZIP 格式!");
                } else if (!isLt2M) {
                    this.$message.error("上传文件大小不能超过 200MB!");
                }
                return isJPG && isLt2M;
            },
            videoBefore(file) {
                // RM、RMVB、3GP、AVI、MPEG、MPG、MKV、DAT、ASF、WMV、FLV，MOV、MP4、OGG、OGM
                const isJPG =
                    file.type === "video/mp4" ||
                    file.type === "video/rm" ||
                    file.type === "video/rmvb" ||
                    file.type === "video/3gp" ||
                    file.type === "video/avi" ||
                    file.type === "video/mpeg" ||
                    file.type === "video/mpg" ||
                    file.type === "video/mkv" ||
                    file.type === "video/dat" ||
                    file.type === "video/asf" ||
                    file.type === "video/wmv" ||
                    file.type === "video/flv" ||
                    file.type === "video/mov" ||
                    file.type === "video/ogg" ||
                    file.type === "video/ogm";
                const isLt2M = file.size / 1024 / 1024 < 200;
                if (!isJPG) {
                    this.$message.error("上传文件只能是MP4,rmvb,avi等影音文件 !");
                } else if (!isLt2M) {
                    this.$message.error("上传文件大小不能超过 200MB!");
                }
                return isJPG && isLt2M;
            },
            // 阿里云 文件上传
            uploadHttp({ file }) {
                this.loading = true;
                this.uploadConfig.bucket = this.uploadConfig.bucketName;
                this.uploadConfig.stsToken = this.uploadConfig.securityToken;
                this.uploadConfig.secure = true;
                const fileName =
                    this.uploadConfig.useDir +
                    this.$route.name +
                    "/" +
                    `${Date.parse(new Date())}` +
                    "*" +
                    file.name; //定义唯一的文件名
                ossClient(this.uploadConfig)
                    .put(fileName, file, {
                        // ContentType: "image/jpeg"
                    })
                    .then(({ res, url, name }) => {
                        if (res && res.status == 200) {
                            if (this.itemData.type == "file") {
                                const arr = name.split("*");
                                url = [{ name: arr[arr.length - 1], url: url }];
                            } else if (this.itemData.type == "imageMore") {
                                this.imageMoreUrl.push({ name: name, url: url, uid: name });
                                this.loading = false;
                                this.firstUpImg = false;
                                this.$emit("uploadSuccess", this.imageMoreUrl);
                                return false;
                            }
                            this.loading = false;
                            this.$emit("uploadSuccess", url);
                        }
                    })
                    .catch(err => {
                        this.loading = false;
                        console.log(`阿里云OSS上传图片失败回调`, err);
                    });
            },
            // 多张图片移除
            imageMoreRemove(file, fileList) {
                this.firstUpImg = false;
                this.imageMoreUrl.forEach((e, i) => {
                    if (e.name == file.name) {
                        // delete this.imageMoreUrl[i];
                        this.imageMoreUrl.splice(i, 1);
                    }
                });
                this.$emit("uploadSuccess", this.imageMoreUrl);
            },

            vidPreview(e) {
                this.dialogFormVisible = true;
            },
            imgMax() {
                this.$message({
                    message: "只能上传 " + this.itemData.limit + " 张图片 !",
                    type: "warning"
                });
            },
            handleExceed() {
                this.$message({
                    message: "只能上传 1 个视频 !",
                    type: "warning"
                });
            },
            beforeRemove(file) {
                // this.$confirm("你是否需要更换改文件 ?", "提示", {
                //   confirmButtonText: "确定",
                //   cancelButtonText: "取消",
                //   type: "warning",
                //   roundButton: true
                // })
                //   .then(() => {
                //     return true;
                //   })
                //   .catch(() => {
                //     return false;
                //     this.$message({
                //       type: "info",
                //       message: "已取消"
                //     });
                //   });
            }
        }
    };
</script>
<style lang="scss" scoped>
    .upload-demo {
        width: 100%;
        ::v-deep .el-list-enter-active {
            -webkit-transition: none;
            transition: none;
            opacity: 0;
            -webkit-transform: none;
            transform: none;
        }
        ::v-deep .el-list-leave-active {
            -webkit-transition: none;
            transition: none;
            opacity: 0;
            -webkit-transform: none;
            transform: none;
        }
        ::v-deep .el-list-enter-to {
            -webkit-transition: none;
            transition: none;
            opacity: 0;
            -webkit-transform: none;
            transform: none;
        }
        ::v-deep .el-list-leave-to {
            -webkit-transition: none;
            transition: none;
            opacity: 0;
            -webkit-transform: none;
            transform: none;
        }
    }
    .vidDialog {
        ::v-deep .el-dialog__body {
            padding: 0px 20px 30px;
            max-height: 800px;
        }
    }
</style>
